﻿using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Cemit.PolyServer
{
    public class ClientState
    {
        public readonly Socket socket;
        public readonly PolyServer server;
        public ByteArray readBuff;
        public long lastPingTime = 0;
        public Player player;
        public event Action<ClientState> OnClosed;

        public bool IsClose { get; private set; }
        public bool IsLogin => player != null;
        public EndPoint IP => socket.RemoteEndPoint;
        
        public ClientState(Socket socket, PolyServer server)
        {
            this.socket = socket;
            this.server = server;

            readBuff = new ByteArray();
            lastPingTime = Time.GetTimeStamp();
        }

        /// <summary>
        /// 关闭连接，如果该连接已登录则一并清除登录
        /// </summary>
        public void Close()
        {
            this.Log("连接已关闭：" + ToInfoString());
            
            IsClose = true;
            OnClosed?.Invoke(this);

            server.RemoveSocket(socket);
            socket.Close();

            if (player != null)
            {
                player.Logout();
            }
        }

        /// <summary>
        /// 如果是已经登录的连接，则输出用户名，否则输出IP
        /// </summary>
        public string ToInfoString()
        {
            return IsLogin ? player.ID : IP.ToString();
        }
    }
}
